package com.sdry.service.impl.llm;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sdry.mapper.hpf.PositionMapper;
import com.sdry.mapper.llm.EmployeeMapper;
import com.sdry.mapper.llm.ProductionReportMapper;
import com.sdry.mapper.llm.TeamMapper;
import com.sdry.mapper.llm.TeamRecordMapper;
import com.sdry.model.hpf.Position;
import com.sdry.model.llm.Employee;
import com.sdry.model.llm.EmployeeRecord;
import com.sdry.model.llm.Team;
import com.sdry.model.llm.TeamRecord;
import com.sdry.model.llm.User;
import com.sdry.model.llm.UserReport;
import com.sdry.service.llm.UserReportService;
import com.sdry.utils.DateUtil;

/**
 * 人员报表
 * @Title:UserReportServiceImp
 * @Package com.sdry.service.impl.llm
 * @author llm
 * @date 2019年1月6日
 * @version 1.0
 */

@Service
public class UserReportServiceImp implements UserReportService {


	@Resource
	private ProductionReportMapper productionReportMapper;
	@Resource
	private PositionMapper positionMapper;
	@Resource
	private TeamRecordMapper teamRecordMapper;
	@Resource
	private TeamMapper teamMapper;
	@Resource
	private EmployeeMapper employeeMapper;
	
	/** 
	 * 人员报表      
	 * @param map
	 * @return    
	 * @throws ParseException 
	 */
	@Override
	public List<UserReport> listAllProductionByTimeAndTeam(Map<String, Object> map) throws ParseException {
		List<UserReport> dateStatusList = new ArrayList<>();
		Long uid = (Long)map.get("uid");
		//如果没有选择员工
		if(0 != uid){
			Integer year = Integer.parseInt(map.get("time").toString().substring(0, 4));
			Integer month = Integer.parseInt(map.get("time").toString().substring(5, 7));
			String startTime = "";
			String endTime = "";
			Long membranePid = null;
			Long assemblePid = null;
			Long centrifugePid = null;
			Long solidifyPid = null;
			Long incisePid = null;
			List<Position> list = positionMapper.listAllPosition();
			for(Position position : list){
				if("膜丝".equals(position.getPname())){
					membranePid = position.getPid();
				}
				if("组装".equals(position.getPname())){
					assemblePid = position.getPid();
				}
				if("离心".equals(position.getPname())){
					centrifugePid = position.getPid();
				}
				if("拆端盖".equals(position.getPname())){
					solidifyPid = position.getPid();
				}
				if("切割".equals(position.getPname())){
					incisePid = position.getPid();
				}
			}
			map.put("membranePid", membranePid);
			map.put("assemblePid", assemblePid);
			map.put("centrifugePid", centrifugePid);
			map.put("solidifyPid", solidifyPid);
			map.put("incisePid", incisePid);
			
			//膜丝工时
			Long mscha = 0L;
			List<EmployeeRecord> membraneList = productionReportMapper.getEmployeeRecordInMS(map);
			for(EmployeeRecord empRecord : membraneList){
				mscha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
			}
			String msWork = DateUtil.time(mscha);
			
			//组装工时
			Long zzcha = 0L;
			List<EmployeeRecord> assembleList = productionReportMapper.getEmployeeRecordInZZ(map);
			for(EmployeeRecord empRecord : assembleList){
				zzcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
			}
			String zzWork = DateUtil.time(zzcha);
			
			//离心工时
			Long lxcha = 0L;
			List<EmployeeRecord> centrifugeList = productionReportMapper.getEmployeeRecordInLX(map);
			for(EmployeeRecord empRecord : centrifugeList){
				lxcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
			}
			String lxWork = DateUtil.time(lxcha);
			
			//拆端盖工时
			Long ghcha = 0L;
			List<EmployeeRecord> solidifyList = productionReportMapper.getEmployeeRecordInGH(map);
			for(EmployeeRecord empRecord : solidifyList){
				ghcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
			}
			String ghWork = DateUtil.time(ghcha);
			
			//切割工时
			Long qgcha = 0L;
			List<EmployeeRecord> inciseList = productionReportMapper.getEmployeeRecordInQG(map);
			for(EmployeeRecord empRecord : inciseList){
				qgcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
			}
			String qgWork = DateUtil.time(qgcha);
			
			//获取当月的天数
			List<String> timelist = DateUtil.getMonthFullDayByYearAndMonth(year, month);
			for(int i = 0; i < timelist.size(); i ++){
				//获取当天的班组
				List<TeamRecord> trList = teamRecordMapper.getTeamByTimeAndUid(map);
				UserReport userReport = new UserReport();
				if(trList.size() > 0){
					Team t = teamMapper.getTeamByTid(trList.get(0).getTeamId());
					if(t.getTname().equals("白班")){
						startTime = timelist.get(i) + " 07:00:00";
						endTime = timelist.get(i) +  " 18:59:59";
					}else{
						startTime = timelist.get(i) +  " 19:00:00";
						String end = DateUtil.getSpecifiedDayAfter(timelist.get(i));
						endTime = end +  " 06:59:59";
					}
					Map<String, Object> timeMap = new HashMap<>();
					timeMap.put("beginTime", startTime);
					timeMap.put("endTime", endTime);
					timeMap.put("uid", uid);
					
					//当天员工在各工位的产量统计
					Integer mosi = productionReportMapper.getCountMSByTimeAndUid(timeMap);  
					Integer zuzhuang = productionReportMapper.getCountZZByTimeAndUid(timeMap);
					Integer lixin = productionReportMapper.getCountLXByTimeAndUid(timeMap);
					Integer guhua = productionReportMapper.getCountGHByTimeAndUid(timeMap);
					Integer qiege = productionReportMapper.getCountQGByTimeAndUid(timeMap);
					
					userReport.setMembrane(mosi + "");
					userReport.setAssemble(zuzhuang + "");
					userReport.setCentrifuge(lixin + "");
					userReport.setSolidify(guhua + "");
					userReport.setIncise(qiege + "");
					userReport.setTeamName(t.getTname());
				}else{
					userReport.setMembrane("0");
					userReport.setAssemble("0");
					userReport.setCentrifuge("0");
					userReport.setSolidify("0");
					userReport.setIncise("0");
					userReport.setTeamName("无记录");
				}
				userReport.setDateTime(timelist.get(i));
				userReport.setUid(uid);
				userReport.setYearMonth(map.get("time").toString());
				//把数据存入集合
				dateStatusList.add(userReport);
			}
			UserReport userReport = new UserReport();
			userReport.setUid(uid);
			userReport.setYearMonth(map.get("time").toString());
			userReport.setDateTime("工时统计");
			userReport.setMembrane(msWork);
			userReport.setAssemble(zzWork);
			userReport.setCentrifuge(lxWork);
			userReport.setSolidify(ghWork);
			userReport.setIncise(qgWork);
			//把工时存入集合
			dateStatusList.add(userReport);
			}
		return dateStatusList;
	}

	/**    
	 * 根据日期和员工ID查询报表      
	 * @param map
	 * @return    
	 */
	@Override
	public List<UserReport> listUserReportByTimeAndUid(Map<String, Object> map) {
		return productionReportMapper.listUserReportByTimeAndUid(map);
	}

	/** 
	 * 新增人员报表      
	 * @param ur    
	 */
	@Override
	public Integer saveUserReport(UserReport ur) {
		return productionReportMapper.saveUserReport(ur);
	}

	/**   
	 * 修改人员报表          
	 * @param ur    
	 */
	@Override
	public Integer updateUserReport(UserReport ur) {
		return productionReportMapper.updateUserReport(ur);
	}

	/**       
	 * 查询当天数据存入数据库    
	 */
	@Override
	public Integer getUserReportByToday(String time) {
		int isSuccess = 0;
		Integer day = Integer.parseInt(time.substring(8,10));
		String month = "";
		if(1 == day){
			// 获取上一个月
			SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(new Date());
	        calendar.add(Calendar.MONTH, -1);
	        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
	        month = dft.format(calendar.getTime());
		}else{
			month = time.substring(0,7);
		}
		//获取某月数据
		List<UserReport> userReportByMonth = productionReportMapper.getUserReportByMonth(month);
		//删除一个月的数据
		Integer i = productionReportMapper.deleteUserReportByMonth(month);
		if(i > 0 || userReportByMonth.size() == 0){
			//从新给表里存数据
			//1、所有的班组员工
			List<User> allUser = employeeMapper.listAllUserInTeam();
			for(User user : allUser){
				Map<String, Object> map = new HashMap<>();
				map.put("time", month);
				map.put("uid", user.getUid());
				try {
					//2、查询一月数据
					List<UserReport> list = listAllProductionByTimeAndTeam(map);
					for(UserReport ur : list){
						//3、保存一月数据
						saveUserReport(ur);
						isSuccess += 1;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return isSuccess;
	}

	/**    
	 * 更新人员报表   
	 * @param month
	 * @return    
	 * @throws ParseException 
	 */
	@Override
	public Integer renewalUserReport(String month) throws ParseException {
		Integer isSuccess = 0;
		boolean bo = false;
		boolean bo2 = false;
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
		Calendar calendars = Calendar.getInstance();
		//获取当前天
		int days = calendars.get(Calendar.DAY_OF_MONTH);// 当前天
		
		//为1查询传的上月
		if (days == 1) {
			calendars.add(Calendar.DAY_OF_MONTH, -1);
			int mon = calendars.get(Calendar.MONTH) + 1;// 获取月份
			Date date = calendars.getTime();
			month = sd.format(date);
		}
		//1、删除该月的数据
		productionReportMapper.deleteUserReportByMonth(month);
		//2、根据人员更新数据（查询所有的生产人员）
		List<Team> listAllTeam = teamMapper.listAllTeam();
		for(Team team : listAllTeam){
			//3、根据班组长ID和时间查询产量和工时
			bo = getYieldByMonthAndUid(month, team.getNum());
			List<Employee> employeeByTid = employeeMapper.findEmployeeByTid(team.getTid());
			//查询班组员工的产量和工时
			for(Employee emp : employeeByTid){
				if(emp.getUid() != team.getNum()){
					bo2 = getYieldByMonthAndUid(month, emp.getUid());
				}
			}
		}
		if(bo && bo2){
			isSuccess = 1;
		}
		return isSuccess;
	}

	/**   
	 * 查询某员工某个月的产量和工时
	 * @Title:getYieldByMonthAndUid   
	 * @param month
	 * @param num             
	 * @throws ParseException 
	 */
	private boolean getYieldByMonthAndUid(String month, Long uid) throws ParseException {
		Integer number = 0;
		List<UserReport> userReportList = new ArrayList<>();
		Integer totalMousse = 0;
		Integer totalAssemble = 0;
		Integer totalCentrifule = 0;
		Integer totalSolid = 0;
		Integer totalCut = 0;
		if(null != uid && !"".equals(uid)){
			Integer year = Integer.parseInt(month.substring(0, 4));
			Integer mon = Integer.parseInt(month.substring(5, 7));
			//获取该月的所有日期
			List<String> timelist = DateUtil.getMonthFullDayByYearAndMonth(year, mon);
			//查询该员工的班组信息
			Team t = teamMapper.getTeamByUid(uid);
			//1、查询该员工一个月的产量
			for(String dateDay : timelist){
				Map<String, Object> map = new HashMap<>();
				map.put("dateDay", dateDay);
				map.put("time", dateDay);
				map.put("uid", uid);
				UserReport userReport = new UserReport();
				//查询当天的班组记录
				List<TeamRecord> trList = teamRecordMapper.getTeamByTimeAndUid(map);
				if(trList.size() > 0){
					Integer mousse = productionReportMapper.getCountMousseByTimeAndUid(map);  
					Integer assemble = productionReportMapper.getCountAssembleByTimeAndUid(map);
					Integer centrifule = productionReportMapper.getCountCentrifuleByTimeAndUid(map);
					Integer solid = productionReportMapper.getCountSolidByTimeAndUid(map);
					Integer cut = productionReportMapper.getCountCutByTimeAndUid(map);
					userReport.setMembrane(mousse + "");
					userReport.setAssemble(assemble + "");
					userReport.setCentrifuge(centrifule + "");
					userReport.setSolidify(solid + "");
					userReport.setIncise(cut + "");
					userReport.setTeamName(t.getTname());
					//产量合计
					totalMousse += mousse;
					totalAssemble += assemble;
					totalCentrifule += centrifule;
					totalSolid += solid;
					totalCut += cut;
				}else{
					userReport.setMembrane("0");
					userReport.setAssemble("0");
					userReport.setCentrifuge("0");
					userReport.setSolidify("0");
					userReport.setIncise("0");
					userReport.setTeamName(t.getTname());
				}
				userReport.setUid(uid);
				userReport.setYearMonth(month);
				userReport.setDateTime(dateDay);
				userReportList.add(userReport);
				
				//把产量存入人员报表
				number += saveUserReport(userReport);
			}
			//把产量合计存入报表
			UserReport productionTotal = new UserReport();
			productionTotal.setMembrane(totalMousse + "");
			productionTotal.setAssemble(totalAssemble + "");
			productionTotal.setCentrifuge(totalCentrifule + "");
			productionTotal.setSolidify(totalSolid + "");
			productionTotal.setIncise(totalCut + "");
			productionTotal.setUid(uid);
			productionTotal.setYearMonth(month);
			productionTotal.setDateTime("产量统计");
			userReportList.add(productionTotal);
			
			//把产量合计存入人员报表
			number += saveUserReport(productionTotal);
			
			//2、查询该员工一个月的工时
			String msWork = "";
			String zzWork = "";
			String lxWork = "";
			String ghWork = "";
			String qgWork = "";
			//如果统计班组长的工时
			if(uid == t.getNum()){
				Map<String, Object> map3 = new HashMap<>();
				map3.put("uid", t.getNum());
				map3.put("dateMonth", month);
				List<EmployeeRecord> empList = teamRecordMapper.getRecordByUidAndMonth(map3);
				//组装工时
				Long zzcha = 0L;
				for(EmployeeRecord empRecord : empList){
					zzcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
				}
				msWork = zzWork = lxWork = ghWork = qgWork = DateUtil.time(zzcha);
			//如果统计员工的工时
			}else{
				Long membranePid = null;
				Long assemblePid = null;
				Long centrifugePid = null;
				Long solidifyPid = null;
				Long incisePid = null;
				List<Position> list = positionMapper.listAllPosition();
				for(Position position : list){
					if("膜丝".equals(position.getPname())){
						membranePid = position.getPid();
					}
					if("组装".equals(position.getPname())){
						assemblePid = position.getPid();
					}
					if("离心".equals(position.getPname())){
						centrifugePid = position.getPid();
					}
					if("拆端盖".equals(position.getPname())){
						solidifyPid = position.getPid();
					}
					if("切割".equals(position.getPname())){
						incisePid = position.getPid();
					}
				}
				Map<String, Object> map = new HashMap<>();
				map.put("uid", uid);
				map.put("time", month);
				map.put("membranePid", membranePid);
				map.put("assemblePid", assemblePid);
				map.put("centrifugePid", centrifugePid);
				map.put("solidifyPid", solidifyPid);
				map.put("incisePid", incisePid);
				
				//膜丝工时
				Long mscha = 0L;
				List<EmployeeRecord> membraneList = productionReportMapper.getEmployeeRecordInMS(map);
				for(EmployeeRecord empRecord : membraneList){
					mscha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
				}
				
				if(mscha == 0L){
					//获取班组长的工时
					map.put("foreman", t.getNum());
					map.put("total", "工时统计");
					msWork = productionReportMapper.getMousseWorkTimeByUserReport(map);
				}else{
					msWork = DateUtil.time(mscha);
				}
				
				//组装工时
				Long zzcha = 0L;
				List<EmployeeRecord> assembleList = productionReportMapper.getEmployeeRecordInZZ(map);
				for(EmployeeRecord empRecord : assembleList){
					zzcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
				}
				
				if(zzcha == 0L){
					//获取班组长的工时
					map.put("foreman", t.getNum());
					map.put("total", "工时统计");
					zzWork = productionReportMapper.getAssembleWorkTimeByUserReport(map);
				}else{
					zzWork = DateUtil.time(zzcha);
				}
				
				//离心工时
				Long lxcha = 0L;
				List<EmployeeRecord> centrifugeList = productionReportMapper.getEmployeeRecordInLX(map);
				for(EmployeeRecord empRecord : centrifugeList){
					lxcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
				}
				
				if(lxcha == 0L){
					//获取班组长的工时
					map.put("foreman", t.getNum());
					map.put("total", "工时统计");
					lxWork = productionReportMapper.getCentrifugeWorkTimeByUserReport(map);
				}else{
					lxWork = DateUtil.time(lxcha);
				}
				
				//拆端盖工时
				Long ghcha = 0L;
				List<EmployeeRecord> solidifyList = productionReportMapper.getEmployeeRecordInGH(map);
				for(EmployeeRecord empRecord : solidifyList){
					ghcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
				}
				
				if(ghcha == 0L){
					//获取班组长的工时
					map.put("foreman", t.getNum());
					map.put("total", "工时统计");
					ghWork = productionReportMapper.getSolidWorkTimeByUserReport(map);
				}else{
					ghWork = DateUtil.time(ghcha);
				}
				
				//切割工时
				Long qgcha = 0L;
				List<EmployeeRecord> inciseList = productionReportMapper.getEmployeeRecordInQG(map);
				for(EmployeeRecord empRecord : inciseList){
					qgcha += DateUtil.workHourse(empRecord.getLoginTime(), empRecord.getLogoutTime());
				}
				
				if(qgcha == 0L){
					//获取班组长的工时
					map.put("foreman", t.getNum());
					map.put("total", "工时统计");
					map.put("dateMonth", month);
					qgWork = productionReportMapper.getWorkTimeByUserReport(map);
				}else{
					qgWork = DateUtil.time(qgcha);
				}
			}
			//把产量合计存入报表
			UserReport workTimeTotal = new UserReport();
			workTimeTotal.setMembrane(msWork);
			workTimeTotal.setAssemble(zzWork);
			workTimeTotal.setCentrifuge(lxWork);
			workTimeTotal.setSolidify(ghWork);
			workTimeTotal.setIncise(qgWork);
			workTimeTotal.setUid(uid);
			workTimeTotal.setYearMonth(month);
			workTimeTotal.setDateTime("工时统计");
			userReportList.add(productionTotal);
			
			//把工时合计存入人员报表
			number += saveUserReport(workTimeTotal);
		}
		if(number == userReportList.size() && userReportList.size() > 0){
			return true;
		}else{
			return false;
		}
		
	}
	
}
